<template>
  <a-list
    v-if="records.length > 0"
    :data="records"
    :loading="loading"
    :bordered="false"
    style="margin-bottom: 16px"
  >
    <template #item="{ item }">
      <a-list-item>
        <a-list-item-meta
          :title="item.title"
          :description="item.tags?.join(' / ')"
        >
          <template #avatar>
            <a-avatar :size="36" :src="item.userAvatar" />
          </template>
        </a-list-item-meta>

        <!-- 操作区 -->
        <template #actions>
          <a-space>
            <a-button size="mini" type="text" @click="editPost(item)">
              编辑
            </a-button>
            <a-button
              size="mini"
              type="text"
              status="danger"
              @click="deletePost(item)"
            >
              删除
            </a-button>
            <a-button size="mini" type="text" @click="toDetail(item.id)">
              查看
            </a-button>
          </a-space>
        </template>

        <!-- 内容摘要 -->
        <a-typography-paragraph :ellipsis="{ rows: 2 }" style="margin-top: 4px">
          {{ item.content }}
        </a-typography-paragraph>
      </a-list-item>
    </template>
  </a-list>

  <!-- 分页 -->
  <a-pagination
    v-model:current="query.current"
    v-model:page-size="query.pageSize"
    :total="total"
    style="margin-top: 16px; text-align: center"
    @change="fetchData"
  />
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import message from "@arco-design/web-vue/es/message";
import { deletePostUsingPost } from "@/api/postController"; // 导入删除接口

// 定义 props
const props = defineProps({
  fetch: Function, // 确保 `fetch` 方法正确传入
});

const router = useRouter();

// 请求状态和数据
const loading = ref(false);
const records = ref<any[]>([]);
const total = ref(0);
const query = reactive({
  current: 1,
  pageSize: 10,
});

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await props.fetch({
      current: query.current,
      pageSize: query.pageSize,
    });
    if (res.data.code === 0) {
      records.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      message.error(res.data.message);
    }
  } finally {
    loading.value = false;
  }
};

const editPost = (item: any) => {
  router.push(`/post/edit/${item.id}`);
};

const deletePost = async (item: any) => {
  const res = await deletePostUsingPost({ id: item.id });
  if (res.data.code === 0) {
    message.success("帖子删除成功");
    fetchData(); // 刷新帖子列表
  } else {
    message.error("删除失败：" + res.data.message);
  }
};

const toDetail = (id: number) => {
  router.push(`/post/detail/${id}`);
};

watch(() => props.fetch, fetchData, { immediate: true });
</script>
